﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightAnimation
{
    public class ScaleTransformAnimation : TransformAnimation<ScaleTransform>
    {
 private double _scale;

        public double Scale
        {
            get { return _scale; }
            set { _scale = value; }
        }

        public ScaleTransformAnimation(FrameworkElement element, double angle, int seconds)
            : base(element, new TimeSpan(0, 0, seconds))
        {
            this.Scale = angle;
        }

        protected override Storyboard CreateStoryboard()
        {
            int index = PrepareElement(Element);
            var XpropertyPath = new PropertyPath(String.Format("(UIElement.RenderTransform).(TransformGroup.Children)[{0}].(ScaleX)", index));
            var YpropertyPath = new PropertyPath(String.Format("(UIElement.RenderTransform).(TransformGroup.Children)[{0}].(ScaleY)", index));
            var storyboard = new Storyboard();
            var Xanimation = new DoubleAnimationUsingKeyFrames();
            var Yanimation = new DoubleAnimationUsingKeyFrames();
            Xanimation.KeyFrames.Add(new EasingDoubleKeyFrame()
            {
                Value = Scale,
                KeyTime = AnimationDuration
            });

            Yanimation.KeyFrames.Add(new EasingDoubleKeyFrame()
            {
                Value = Scale,
                KeyTime = AnimationDuration
            });
            Storyboard.SetTarget(Xanimation, Element);
            Storyboard.SetTarget(Yanimation, Element);
            Storyboard.SetTargetProperty(Xanimation, XpropertyPath);
            Storyboard.SetTargetProperty(Yanimation, YpropertyPath);
            storyboard.Children.Add(Xanimation);
            storyboard.Children.Add(Yanimation);
            return storyboard;
        }
        protected override void ApplyValues(Storyboard storyboard)
        {
            if (storyboard == null)
                throw new ArgumentNullException("storyboard");

            var animation = storyboard.Children[0] as DoubleAnimationUsingKeyFrames;
            animation.KeyFrames[0].Value = Scale;
            animation.KeyFrames[0].KeyTime = KeyTime.FromTimeSpan(AnimationDuration);
        }
        public static void AnimateScale(FrameworkElement element, double scale, int seconds)
        {
            new ScaleTransformAnimation(element, scale, seconds).Apply();
        }
    }
}
